package com.huifaapp.mall.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.Specialactivity;
import com.huifaapp.mall.adapter.BabyAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.BabyBean;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ShareUtils;
import com.huifaapp.mall.uitils.ToastUtil;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * A simple {@link Fragment} subclass.
 */
public class BabyFragment extends Fragment {
    private XRecyclerView baby_Xrecy;
    private BabyAdapter babyAdapter;
    private List<BabyBean.DataBean.ListBean>goods;
    int curr;
    private ImageView iv_babyfragment;
    private static final int SHARET_WXHY = 517;
    public static Map<Integer, Boolean> hmap;

    ArrayList<String> idlist = new ArrayList<>();
    public BabyFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_baby,container,false);
        hmap = new HashMap<>();
        initView(view);
        return view;
    }

    private void initView(View view) {
        goods = new ArrayList<>();
        baby_Xrecy = (XRecyclerView) view.findViewById(R.id.baby_xrecy);
        iv_babyfragment= (ImageView) view.findViewById(R.id.iv_babyfragment);
        baby_Xrecy.setLayoutManager(new GridLayoutManager((getActivity()), 2 ,GridLayoutManager.VERTICAL,false));
        babyAdapter = new BabyAdapter(getActivity(),goods);
        baby_Xrecy.setAdapter(babyAdapter);
        baby_Xrecy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                curr = 0;
                requestEmit();
            }

            @Override
            public void onLoadMore() {
                curr++;
                requestEmit();
            }
        });
        if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            iv_babyfragment.setVisibility(View.VISIBLE);
        }else{
            iv_babyfragment.setVisibility(View.GONE);
        }
        requestEmit();
        iv_babyfragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Contig.checkedIndexBABY.size() == 0) {
                    Toast.makeText(getActivity(), "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < Contig.checkedIndexBABY.size(); i++)
                        idlist.add(goods.get(Contig.checkedIndexBABY.get(i)).getId());

                    Log.e("数据Toady", idlist + "-===========id");


                    StringBuffer permission = new StringBuffer();
                    for (int i = 0; i < idlist.size(); i++) {
                        if (i == 0) {
                            permission.append(idlist.get(i));
                        } else {
                            permission.append("," + idlist.get(i));
                        }
                        Contig.listididBABY.add(idlist.get(i));

                    }
//                    LoadStoreList(0, 0, Contig.listidid);

                    ApiManager
                            .getInstance()
                            .getApiServer()
                            .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(getActivity()), permission.toString())
                            .compose(ApiManager.<ShareImageBean>handlResult())
                            .subscribe(new ObserverCallback<ShareImageBean>(getActivity()) {
                                @Override
                                protected void onSuccessful(ShareImageBean resp) {

                                    saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                    if (Contig.checkedIndexBABY.size() > 0) {
                                        for (int a = 0; a < Contig.checkedIndexBABY.size(); a++) {
                                            Contig.ShareListBABY.add(goods.get(Contig.checkedIndexBABY.get(a)).getId());
                                        }
                                    }
                                    babyAdapter = new BabyAdapter(getActivity(),goods);
                                    baby_Xrecy.setAdapter(babyAdapter);

                                }

                                @Override
                                protected void onError(String code, String errMsg) {
                                    ToastUtils.showShortSafe(errMsg);
                                }
                            });
                    idlist.clear();
                }
            }
        });
    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran", "------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {
                            case SHARET_WXHY:


                                ShareUtils.sharePicToFriendNoSDK(getActivity(), value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });

    }
    private void requestEmit(){
        System.out.println("response curr = " + curr);
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/mycollectlist")
                //token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
                .addParams("start",curr + "")
                .addParams("length",10 + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {}
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response = " + response);
                        baby_Xrecy.refreshComplete();
                        initData(response);
                    }
                });
    }

    private void initData(String response) {
        Gson gson = new Gson();
        BabyBean babyBean = gson.fromJson(response,BabyBean.class);
        if (babyBean != null && babyBean.getData() != null && babyBean.getData().getList() != null) {
            if (curr == 0) {
                goods.clear();
            }
            goods.addAll(babyBean.getData().getList());
            babyAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showL(getActivity(), "data is error");
        }
    }
}
